package com.ljz.servlet;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.ljz.dao.EmpDao;
import com.ljz.entity.Employ;
import com.ljz.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/searchName")
public class EmpSearchNameServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数的值
        Integer currentPage = Integer.valueOf(req.getParameter("currentPage"));
        Integer pageSize = Integer.valueOf(req.getParameter("pageSize"));
        String ename = req.getParameter("ename");
        //获取dao层对象
        SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
        EmpDao empDao = sqlSession.getMapper(EmpDao.class);
        //开始分页
        PageHelper.startPage(currentPage,pageSize);
        List<Employ> empByName = empDao.findEmpByName(ename);
        PageInfo<Employ> pageInfo = new PageInfo<>(empByName);
        //查到数据就释放资源
        sqlSession.close();
        //将结果json序列化
        Gson gson = new Gson();
        String json = gson.toJson(pageInfo);
        //将结果返回到前端
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(json);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
